<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="场地编号" prop="serialNumber">
        <el-input
          v-model="queryParams.serialNumber"
          placeholder="请输入场地编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-input
          v-model="queryParams.category"
          placeholder="请输入分类"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="外部名称" prop="externalName">
        <el-input
          v-model="queryParams.externalName"
          placeholder="请输入外部名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出租状态" prop="rentalStatus">
        <el-select v-model="queryParams.rentalStatus" placeholder="请选择出租状态" clearable>
          <el-option
            v-for="dict in dict.type.admin_rental_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否启用" prop="isActive">
        <el-select v-model="queryParams.isActive" placeholder="请选择是否启用" clearable>
          <el-option
            v-for="dict in dict.type.admin_is_active"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['plot:plot:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['plot:plot:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['plot:plot:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['plot:plot:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="plotList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="场地编号" align="center" prop="serialNumber" />
      <el-table-column label="分类" align="center" prop="category" />
      <el-table-column label="面积" align="center" prop="area" />
      <el-table-column label="外部名称" align="center" prop="externalName" />
      <el-table-column label="出租状态" align="center" prop="rentalStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.admin_rental_status" :value="scope.row.rentalStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="description" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="是否启用" align="center" prop="isActive">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.admin_is_active" :value="scope.row.isActive"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['plot:plot:edit']"
          >修改</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-link"
            @click="handleBindFruits(scope.row.id)"
          >绑定蔬果</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleViewCrops(scope.row.id)"
          >已绑定果蔬</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改后台-菜园对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="场地编号" prop="serialNumber">
          <el-input v-model="form.serialNumber" placeholder="请输入场地编号" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-input v-model="form.category" placeholder="请输入分类" />
        </el-form-item>
        <el-form-item label="面积" prop="area">
          <el-input v-model="form.area" placeholder="请输入面积" />
        </el-form-item>
        <el-form-item label="外部名称" prop="externalName">
          <el-input v-model="form.externalName" placeholder="请输入外部名称" />
        </el-form-item>
        <el-form-item label="中心点经度" prop="centerLng">
          <el-input v-model="form.centerLng" placeholder="请输入中心点经度" />
        </el-form-item>
        <el-form-item label="中心点纬度" prop="centerLat">
          <el-input v-model="form.centerLat" placeholder="请输入中心点纬度" />
        </el-form-item>
        <el-form-item label="出租状态" prop="rentalStatus">
          <el-select v-model="form.rentalStatus" placeholder="请选择出租状态">
            <el-option
              v-for="dict in dict.type.admin_rental_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="是否启用" prop="isActive">
          <el-select v-model="form.isActive" placeholder="请选择是否启用">
            <el-option
              v-for="dict in dict.type.admin_is_active"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 绑定蔬果对话框 -->
    <el-dialog title="绑定蔬果" :visible.sync="bindFruitsDialog" width="500px" append-to-body>
      <el-form ref="bindFruitsForm" :model="bindFruitsForm" label-width="80px">
        <el-form-item label="选择蔬果">
          <el-select v-model="selectedCropIds" multiple placeholder="请选择蔬果品种">
            <el-option v-for="crop in cropList" :key="crop.id" :label="crop.cropName" :value="crop.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="bindFruitsDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitBindFruits">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 已绑定果蔬对话框 -->
    <el-dialog title="已绑定果蔬" :visible.sync="viewCropsDialog" width="600px" append-to-body>
      <el-table :data="boundCropsList" stripe style="width: 100%">
        <el-table-column prop="cropId" label="作物ID" width="80" align="center"></el-table-column>
        <el-table-column prop="cropName" label="作物名称" align="center"></el-table-column>
        <el-table-column prop="estimatedHarvestTime" label="预计收获时间" align="center">
          <template slot-scope="scope">
            {{ scope.row.estimatedHarvestTime }}
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewCropsDialog = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPlot, getPlot, delPlot, addPlot, updatePlot, listAllCrop, addPlantToPlot, findCropList } from "@/api/plot/plot"

export default {
  name: "Plot",
  dicts: ['admin_rental_status', 'admin_is_active'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 后台-菜园表格数据
      plotList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        serialNumber: null,
        category: null,
        externalName: null,
        rentalStatus: null,
        isActive: null,
      },
      // 表单参数
      form: {},
      // 绑定蔬果相关
      bindFruitsDialog: false,
      currentPlotId: null,
      cropList: [],
      selectedCropIds: [],
      bindFruitsForm: {},
      // 已绑定果蔬相关
      viewCropsDialog: false,
      boundCropsList: [],
      // 表单校验
      rules: {
        serialNumber: [
          { required: true, message: "场地编号不能为空", trigger: "blur" }
        ],
        category: [
          { required: true, message: "分类不能为空", trigger: "blur" }
        ],
        area: [
          { required: true, message: "面积不能为空", trigger: "blur" }
        ],
        externalName: [
          { required: true, message: "外部名称不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询后台-菜园列表 */
    getList() {
      this.loading = true
      listPlot(this.queryParams).then(response => {
        this.plotList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        serialNumber: null,
        category: null,
        area: null,
        externalName: null,
        centerLng: null,
        centerLat: null,
        rentalStatus: null,
        description: null,
        remark: null,
        createdAt: null,
        createdBy: null,
        updatedAt: null,
        updatedBy: null,
        isActive: null,
        isDeleted: null,
        deletedAt: null,
        tenantId: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加后台-菜园"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getPlot(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改后台-菜园"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePlot(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addPlot(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除后台-菜园编号为"' + ids + '"的数据项？').then(function() {
        return delPlot(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('plot/plot/export', {
        ...this.queryParams
      }, `plot_${new Date().getTime()}.xlsx`)
    },

    /** 绑定蔬果按钮操作 */
    handleBindFruits(plotId) {
      this.currentPlotId = plotId
      this.selectedCropIds = []
      this.bindFruitsDialog = true
      this.getAllCropList()
    },

    /** 获取所有果蔬品种 */
    getAllCropList() {
      this.loading = true
      listAllCrop().then(response => {
        this.cropList = response.data
        this.loading = false
      })
    },

    /** 提交绑定蔬果 */
    submitBindFruits() {
      if (this.selectedCropIds.length === 0) {
        this.$modal.msgWarning("请至少选择一个蔬果品种")
        return
      }
      const data = {
        plotId: this.currentPlotId,
        cropIds: this.selectedCropIds
      }
      
      addPlantToPlot(data).then(response => {
        this.$modal.msgSuccess("绑定成功")
        this.bindFruitsDialog = false
        this.getList()
      })
    },

    /** 查看已绑定果蔬按钮操作 */
    handleViewCrops(plotId) {
      this.currentPlotId = plotId
      this.viewCropsDialog = true
      this.fetchBoundCrops()
    },

    /** 获取已绑定的果蔬列表 */
    fetchBoundCrops() {
      this.loading = true
      findCropList(this.currentPlotId).then(response => {
        this.boundCropsList = response.data
        this.loading = false
      }).catch(() => {
        this.loading = false
        this.$modal.msgError("获取已绑定果蔬列表失败")
      })
    }
  }
}
</script>
